<template>
	<div>
		<div class="container mt-2">
			<a-row :gutter="20">
				<a-col :span="14">
					<div class="toolbar">
						<a-space>
							<a-button v-permission="173" type="primary" @click="addNode('company')">
								<plus-outlined />创建公司
							</a-button>

							<a-tooltip placement="topLeft" title="请先点击分公司或上级部门">
								<a-button v-permission="174" type="primary" :disabled="!selectedKeys.length" @click="addNode('department')">
									<plus-outlined />新建部门
								</a-button>
							</a-tooltip>

							<a-tooltip placement="topLeft" title="请先勾选分公司或部门">
								<a-popconfirm title="确定要删除选中的公司或部门吗？" ok-text="是" cancel-text="否" @confirm="deleteNode">
									<a-button v-permission="175" danger :disabled="!checkedKeys?.checked?.length">
										<delete-outlined />批量删除
									</a-button>
								</a-popconfirm>
							</a-tooltip>

							<a-upload v-if="formState.type > 1" v-permission="177" name="upload" :data="{department_id: formState.id}" :show-upload-list="false" :action="`${baseURL}/user/import`" :headers="{Authorization:`Bearer ${proxy.$cookies.get('token')}`}" :before-upload="()=>uploading=true" @change="importUser">
								<a-button>
									<template v-if="uploading">
										<loading-outlined />导入中...
									</template>
									<template v-else>
										<import-outlined />导入用户
									</template>
								</a-button>
							</a-upload>
							<a-button v-else v-permission="177" :disabled="true">
								<import-outlined />导入用户
							</a-button>
						</a-space>
					</div>

					<a-alert v-if="currentNodeState?.name" class="mt-2" :message="`当前选择：${currentNodeState?.name || ''}`"></a-alert>

					<div class="tree mt-2">
						<a-input-search v-model:value="nodeSearchValue" class="mb-2" />
						<a-tree v-if="treeData?.length" v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys" v-model:checkedKeys="checkedKeys" :auto-expand-parent="autoExpandParent" :field-names="{key: 'value'}" checkable :check-strictly="true" :tree-data="treeData" @expand="expandTree" @select="selectTree">
							<template #title="node">
								<span v-html="node.name.replace(nodeSearchValue, `<b style=\'color:#f60\'>${nodeSearchValue}</b>`)"></span>

								<a-space v-if="node.type==3" style="margin-left:20px">
									<!-- <a-button size="small" @click.stop="(e)=>{console.log(node)}">创建工号</a-button> -->
									<a-button v-permission="178" size="small" @click.stop="saveGonghao(node)">创建工号</a-button>
									<!-- <a-button size="small" @click.stop="gonghao(node)">管理工号</a-button> -->
								</a-space>
							</template>
						</a-tree>

						<a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" />
					</div>
				</a-col>
				<a-col :span="10">
					<a-alert message="点击左侧公司或部门，修改基本信息。" type="info" closable />
					<a-tabs>
						<a-tab-pane v-if="formState?.id" key="1" tab="基本信息">
							<a-form ref="formRef" :model="formState" :label-col="{span: 6}" :rules="rulesOptions" @finish="saveInfo">
								<a-form-item label="机构类型" name="type">
									<a-radio-group v-model:value="formState.type">
										<a-radio :value="1" disabled>总部</a-radio>

										<a-radio :value="2" :disabled="formState.type === 1">部门</a-radio>
										<a-radio :value="3" :disabled="formState.type === 1">项目部</a-radio>
										<a-radio :value="4" :disabled="formState.type === 1">工号</a-radio>
										<a-radio :value="5" :disabled="formState.type === 1">城市公司</a-radio>
										<a-radio :value="6" :disabled="formState.type === 1">专业公司</a-radio>
									</a-radio-group>
								</a-form-item>

								<a-form-item :label="`${formState.type === 1 ? '公司' : '部门'}名称`" name="name">
									<a-input v-model:value="formState.name" />
								</a-form-item>

								<a-form-item label="公司城市名称" name="company_name">
									<a-input v-model:value="formState.company_name" placeholder="请输入公司城市名称" />
								</a-form-item>

								<a-form-item label="机构编码" name="code">
									<a-input v-model:value="formState.code" />
								</a-form-item>

								<a-form-item v-if="formState.type > 1" label="上级机构" name="parent_value">
									<a-tree-select v-model:value="formState.parent_value" :show-search="true" :dropdown-style="{}" tree-default-expand-all :tree-data="parentTreeData" :field-names="{children: 'children',label: 'label',value: 'value'}" tree-node-filter-prop="label"></a-tree-select>
								</a-form-item>

								<a-form-item label="排序" name="sort" :wrapper-col="{span: 6}">
									<a-input v-model:value="formState.sort" placeholder="0" />
								</a-form-item>

								<a-form-item label="负责人" name="leader">
									<a-input v-model:value="formState.leader" />
								</a-form-item>
								<a-form-item label="电话" name="phone">
									<a-input v-model:value="formState.phone" placeholder="请输入电话号码" />
								</a-form-item>

								<a-form-item label="区域" name="region">
									<a-cascader v-model:value="formState.region" :check-strictly="true" :options="regionOptions" :load-data="loadRegionData" placeholder="请选择区域" change-on-select />
								</a-form-item>

								<a-form-item label="地址" name="address">
									<a-input v-model:value="formState.address" placeholder="请输入地址" />
								</a-form-item>

								<a-form-item label="备注" name="memo">
									<a-textarea v-model:value="formState.memo" />
								</a-form-item>

								<a-form-item :wrapper-col="{offset: 6}">
									<a-space>
										<a-button v-permission="176" type="primary" html-type="submit">
											<save-outlined />提交
										</a-button>

										<a-button v-permission="175" danger @click="deleteInfo">
											<delete-outlined />删除
										</a-button>
									</a-space>
								</a-form-item>
							</a-form>
						</a-tab-pane>
					</a-tabs>
				</a-col>
			</a-row>
		</div>

		<a-modal v-model:visible="visible.company" title="添加公司" width="400px" @ok="saveNode('company')">
			<a-form ref="nodeRef" :model="nodeState" layout="vertical" v-bind="{labelCol: { style: { width: '100px' } }}">
				<a-form-item label="公司名称" :rules="{ required: true, message: '请输入公司名称', trigger: 'blur' }" name="name">
					<a-input v-model:value="nodeState.name" />
				</a-form-item>
			</a-form>
		</a-modal>

		<a-modal v-model:visible="visible.department" title="添加部门" width="400px" @ok="saveNode('department')">
			<a-form ref="nodeRef" :model="nodeState" layout="vertical" v-bind="{labelCol: { style: { width: '100px' } }}">
				<a-form-item label="部门名称" :rules="{ required: true, message: '请输入部门名称', trigger: 'blur' }" name="name">
					<a-input v-model:value="nodeState.name" />
				</a-form-item>
				<a-form-item label="机构类型" :rules="{ required: true, message: '请选择机构类型', trigger: 'blur' }" name="type">
					<a-radio-group v-model:value="nodeState.type">
						<a-radio :value="2">部门</a-radio>
						<a-radio :value="3">项目部</a-radio>
						<a-radio :value="4">工号</a-radio>
					</a-radio-group>
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>
<script setup>
import { ref, watch, toRefs, reactive, getCurrentInstance, computed } from "vue";
import { Empty } from "ant-design-vue";

import { PlusOutlined, SaveOutlined, DeleteOutlined, LoadingOutlined, ImportOutlined } from "@ant-design/icons-vue";

/*
const expandedKeys = ref([]);
const selectedKeys = ref([]);
const checkedKeys = ref([]);
*/

const { expandedKeys, selectedKeys, checkedKeys } = toRefs(
	reactive({
		expandedKeys: [],
		selectedKeys: [],
		checkedKeys: []
	})
);

import { post, treeToList } from "../utils";

const treeData = ref();
const initTreeData = ref();

const autoExpandParent = ref(true);

const initData = () => {
	post("company/tree").then(data => {
		treeData.value = data;
		initTreeData.value = JSON.parse(JSON.stringify(data));
		if (expandedKeys.value.length === 0) {
			//默认展开所有
			expandedKeys.value = treeToList(JSON.parse(JSON.stringify(data)), [])
				.filter(d => d.parent_id === 0)
				.map(d => d?.parent_value || "0-0");
		}
		console.log(treeData);
	});
};
initData();

const nodeSearchValue = ref();
watch(nodeSearchValue, value => {
	treeData.value = JSON.parse(JSON.stringify(initTreeData.value));
	if (!value) {
		expandedKeys.value = treeToList(JSON.parse(JSON.stringify(treeData.value)), [])
			.filter(d => d.parent_id === 0)
			.map(d => d?.parent_value || "0-0");
	} else {
		const ergodicTree = (trees, index) => {
			const tree = trees[index];
			tree.children = tree.children || [];
			for (let i = 0; i < tree.children.length; i++) {
				ergodicTree(tree.children, i);
			}
			tree.children = tree.children.filter(i => i);
			if (tree.children.length) return;
			if (tree.name.indexOf(value) === -1) {
				delete trees[index];
			}
		};
		const tree = JSON.parse(JSON.stringify(treeData.value));
		ergodicTree(tree, 0);
		treeData.value = tree.filter(item => item);
		expandedKeys.value = treeToList(JSON.parse(JSON.stringify(treeData.value)), []).map(d => d?.parent_value || "0-0");
	}
	autoExpandParent.value = true;
});

const formState = ref({});
const formRef = ref();
const rulesOptions = ref({
	type: [{ required: true, message: "请选择类型", trigger: "blur" }],
	name: [{ required: true, message: "请输入名称" }]
	//company_name: [{ required: true, message: "请输入公司城市名称" }],
});
watch(
	() => formState.value.type,
	val => {
		// 清除校验提示
		if (formRef.value) {
			formRef.value.clearValidate();
		}
		const initRulesOptions = {
			type: [{ required: true, message: "请选择类型", trigger: "blur" }],
			name: [{ required: true, message: "请输入名称" }],
			company_name: [{ required: true, message: "请输入公司城市名称" }]
		};
		if (val === 3) {
			initRulesOptions.leader = [{ required: true, message: `请输入负责人名称` }];
			initRulesOptions.phone = [{ required: true, message: `请输入电话号码` }];
			initRulesOptions.region = [{ required: true, message: `请选择区域` }];
			initRulesOptions.address = [{ required: true, message: `请输入地址` }];
		}
		rulesOptions.value = initRulesOptions;
	}
);

const selectTree = async (selectedKeys, e) => {
	const data = e.node.dataRef;

	currentNodeState.value = { ...data };

	//const region = JSON.parse(data.region || "[]").map(d => parseInt(d));
	const region = data.region;

	//处理懒加载数据
	try {
		if (region[1]) regionOptions.value.find(d => d.value === parseInt(region[0])).children = await getRegion(region[0]);
		if (region[2]) regionOptions.value.find(d => d.value === parseInt(region[0])).children.find(d => d.value === parseInt(region[1])).children = await getRegion(region[1]);
	} catch (err) {
		//proxy.$message.error(err);
	}

	formState.value = { ...data, type: data.type || (data.value.split("-")[1] === "0" ? 1 : 2), region };
};

const expandTree = keys => {
	expandedKeys.value = keys;
	autoExpandParent.value = false;
};

const currentNodeState = ref();

const visible = reactive({
	company: false,
	department: false
});

const addNode = type => {
	if (type === "department" && !currentNodeState.value?.id) {
		proxy.$message.error("请先选择归属公司");
		return;
	}
	visible[type] = true;
	nodeState.value = {
		type: type === "department" ? 2 : 1
	};
};

const nodeRef = ref();
const nodeState = ref({});
const saveGonghao = node => {
	currentNodeState.value = node;

	if (!currentNodeState.value?.id) {
		proxy.$message.error("请先选择归属公司");
		return;
	}
	visible.department = true;
	nodeState.value = {
		type: 4
	};
};
const { proxy } = getCurrentInstance();

const saveNode = type => {
	nodeRef.value
		.validate()
		.then(async () => {
			proxy.$message.destroy();

			const params = { ...nodeState.value };
			if (type === "company") {
				post("company/save", params).then(() => {
					initData();
					visible[type] = false;
					proxy.$message.success("公司信息提交成功");
				});
			} else {
				const { value } = currentNodeState.value;
				const [company_id, department_id] = value.split("-");

				params.company_id = company_id;
				params.parent_id = department_id;

				post("department/save", params).then(() => {
					initData();
					visible[type] = false;
					proxy.$message.success("部门信息提交成功");
				});
			}
		})
		.catch(err => {});
};

const deleteNode = () => {
	if (!checkedKeys.value?.checked?.length) {
		proxy.$message.error("请先选择需要删除的组织");
		return;
	}

	post("company/delete", { id: checkedKeys.value.checked.join(",") }).then(() => {
		proxy.$message.success("删除成功");

		initData();
	});
};

const saveInfo = async () => {
	const params = { ...formState.value };
	if (params.type === 1) {
		params.region = JSON.stringify(params.region || []);

		await post("company/save", params);
	} else {
		const [company_id, department_id] = params.parent_value.split("-");
		params.company_id = company_id;
		params.parent_id = department_id;

		if (params.region) params.region = JSON.stringify(params.region);

		await post("department/save", params);
	}

	initData();
	proxy.$message.success(`${params.type === 1 ? "公司" : "部门"}信息提交成功`);
};

const deleteInfo = async () => {
	let content;
	if (formState.value.type === 1) {
		content = "将同时删除该公司下的所有部门，请谨慎操作";
	} else {
		content = "将同时删除该部门下的所有子部门，请谨慎操作";
	}
	proxy.$confirm({
		title: "确认提示",
		content,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			const { value } = formState.value;
			post("company/delete", { id: value }).then(() => {
				proxy.$message.success("删除成功");

				formState.value = {};
				initData();
			});
		}
	});
};

const getRegion = async parentId => {
	return await post("region/cascader", { parent_id: parentId });
};

const regionOptions = ref([]);
getRegion(0).then(data => {
	regionOptions.value = data;
});

const loadRegionData = options => {
	const option = options[options.length - 1];
	option.loading = true;

	return getRegion(option.value).then(data => {
		option.loading = false;
		option.children = data;

		regionOptions.value = [...regionOptions.value];
	});
};

const parentTreeData = computed(() => {
	const filter = (tree, data = []) => {
		if (!tree.length) return [];

		for (const item of tree) {
			if (item.value === formState.value.value) continue;

			if (item.children && item.children.length > 0) item.children = filter(item.children, []);
			data.push(item);
		}

		return data;
	};

	return filter(JSON.parse(JSON.stringify(treeData.value)));
});

import { baseURL } from "../utils/request";

const uploading = ref(false);

const importUser = ({ file }) => {
	if (file.status !== "done") return;

	uploading.value = false;
	proxy.$message.success("用户导入成功");
};
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
